package cyberdict.scr;

import java.util.ArrayList;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;

public class DictEngine {
	private SQLiteDatabase mDB=null;
	private String mDBName;
	private String mDBPath;
	public ArrayList<String> lstCurrentWord = null;
	public ArrayList<String> lstCurrentContent = null;
	public String dbExtension=".db";
	
	public DictEngine()
	{
		lstCurrentContent = new ArrayList<String>();
    	lstCurrentWord = new ArrayList<String>();
	}
	public DictEngine(String basePath, String dbName)
	{
		lstCurrentContent = new ArrayList<String>();
    	lstCurrentWord = new ArrayList<String>();
    	
		this.setDatabaseFile(basePath, dbName);
	}
	public boolean setDatabaseFile(String basePath, String dbName)
	{
		if (mDB != null)
		{
			if (mDB.isOpen() == true) // Database is already opened
			{
				return true;
				
			}
		}
		
		String fullDbPath="";
		
		try
		{
			fullDbPath = basePath +"/"+ dbName + "/" + dbName + dbExtension;
			mDB = SQLiteDatabase.openDatabase(fullDbPath, null, SQLiteDatabase.OPEN_READWRITE|SQLiteDatabase.NO_LOCALIZED_COLLATORS);
		}
		catch (SQLiteException ex)
		{
			ex.printStackTrace();
			return false; 
		}
		
		if (mDB == null)
		{
			return false;
		}
		
		this.mDBName = dbName;
		this.mDBPath = basePath;
		
		return true;
	}
	public Cursor getCursorWordList(String word)
	{
		
		String query;
		// encode input
		String wordEncode = Utility.encodeContent(word);

		if (word.equals("") || word == null)
		{
			query = "SELECT id,word FROM " + mDBName + " LIMIT 0,5" ;
		}
		else
		{
		    query = "SELECT id,content,word FROM " + mDBName + " WHERE  word >= '"+wordEncode+"' LIMIT 0,15";
		}
		//Log.i(SQL_TAG, "query = " + query);
		
	   	Cursor result = mDB.rawQuery(query,null);
	   	
	   	return result;		
	}

	public Cursor getCursorContentFromWord(String word)
	{
		String query;
		// encode input
		
		String wordEncode = Utility.encodeContent(word);
		{
			query = "SELECT content FROM " + mDBName + " WHERE word = '" + wordEncode +"' Limit 0,1";
		}
		
	   	Cursor result = mDB.rawQuery(query,null);
	   	
	   	return result;		
	}
	public void closeDatabase()
	{
		mDB.close();
	}
	
	public boolean isOpen()
	{
		return mDB.isOpen();
	}
	
	public boolean isReadOnly()
	{
		return mDB.isReadOnly();
	}
	
}
